<template>
  <div>
    <div class="box loginBox" v-if="showLogin == true">
      <div class="title"  >
        <span class="t1">
          <span v-if="showPasswordLogin && !showPersonWechatLogin">登录</span>
          <span v-if="!showPasswordLogin && !showPersonWechatLogin">微信公众号登录</span>
          <span v-if="showPersonWechatLogin">微信扫码登录</span>
        </span>
        <div class="t2" @click="closeLogin()">
          X
        </div>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>

      <el-form :label-position="labelPosition" :rules="loginRules" :model="loginForm" ref="loginForm">

        <!--账号密码登录-->
        <div class="passwordLogin" v-if="showPasswordLogin && !showPersonWechatLogin">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="loginForm.userName" placeholder="请输入用户名或邮箱" :disabled="loginType.password"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" :disabled="loginType.password"></el-input>
          </el-form-item>
          <el-row class="btn">
            <el-button class="loginBtn" type="primary" @click="startLogin" :disabled="loginType.password">登录</el-button>
            <el-button class="registerBtn" type="info" @click="goRegister" :disabled="loginType.password">注册</el-button>
          </el-row>
        </div>

        <!--微信登录-->
        <div v-if="showPersonWechatLogin" style="text-align: center" class="block">

          <div id="login_container" style="text-align: center"></div>

          <Qrcode v-if="wechatOrCode" :text="wechatOrCode" :size="200" style="margin-left: 25%"/>
<!--          <el-row v-if="wechatLoginKey.loginKey.length > 6">-->
<!--            <span style="color: red; font-weight: bold">{{wechatLoginKey.loginKey}}</span>-->
<!--            <i class="el-icon-refresh" @click="refreshWechat()" style="cursor: pointer"></i>-->
<!--          </el-row>-->
        </div>

        <!--微信公众号登录-->
        <div v-if="!showPasswordLogin && !showPersonWechatLogin" style="text-align: center" class="block">
          <el-image :src="webConfig.wechatPhoto" style="width: 200px; height: 200px"></el-image>
          <el-row>
            <span style="font-size: 14px; color: #303133">扫码关注公众号，回复验证码完成登录</span>
          </el-row>
          <el-row>
            <span style="font-size: 14px; color: #303133">登录验证码：</span>
            <span style="color: red; font-weight: bold">{{wechatLoginKey.loginKey}}</span>
            <i class="el-icon-refresh" @click="refreshWechat()" style="cursor: pointer"></i>
          </el-row>
        </div>


        <el-collapse style="margin-top: 5px;" v-model="webConfig.spreadLoginType == '1'? 'open':''">
          <el-collapse-item name="open">
            <template slot="title" style="margin: 0 auto;">
              <el-row style="width: 100%; text-align: center; color: #909399;">
                更多登录方式
              </el-row>
            </template>

            <el-row class="elRow">

              <el-tooltip content="账号登录" style="z-index: 3005" placement="bottom" v-if="!loginType.password">
                <el-button type="info" circle @click="goAuth('password')" :disabled="loginType.password">
                  <span class="iconfont">&#xe8b2;</span>
                </el-button>
              </el-tooltip>

              <el-tooltip content="码云登录" style="z-index: 3005" placement="bottom" v-if="!loginType.gitee">
                <el-button type="danger" circle @click="goAuth('gitee')" :disabled="loginType.gitee">
                  <span class="iconfont">&#xe602;</span>
                </el-button>
              </el-tooltip>

              <el-tooltip content="Github登录" style="z-index: 3005" placement="bottom" v-if="!loginType.github">
                <el-button type="info" circle @click="goAuth('github')" :disabled="loginType.github">
                  <span class="iconfont">&#xe64a;</span>
                </el-button>
              </el-tooltip>

              <el-tooltip content="QQ登录" style="z-index: 3005" placement="bottom" v-if="!loginType.qq">
                <el-button type="primary" circle @click="goAuth('qq')" :disabled="loginType.qq">
                  <span class="iconfont">&#xe601;</span>
                </el-button>
              </el-tooltip>

              <el-tooltip content="公众号登录" style="z-index: 3005" placement="bottom" v-if="!loginType.wechat">
                <el-button type="success" circle @click="goAuth('wechat')" :disabled="loginType.wechat">
                  <span class="iconfont">&#xe60b;</span>
                </el-button>
              </el-tooltip>

              <el-tooltip content="微信登录" style="z-index: 3005" placement="bottom" v-if="!loginType.personWechat">
                <el-button type="success" circle @click="goAuth('personWechat')" :disabled="loginType.personWechat">
                  <span class="iconfont">&#xe66f;</span>
                </el-button>
              </el-tooltip>

            </el-row>
            <div class="loginTip">目前登录方式支持:
              <span v-if="!loginType.password"> 账号密码 </span>
              <span v-if="!loginType.gitee"> 码云 </span>
              <span v-if="!loginType.github"> Github </span>
              <span v-if="!loginType.qq"> QQ </span>
              <span v-if="!loginType.wechat"> 公众号 </span>
              <span v-if="!loginType.personWechat"> 微信 </span>
            </div>
          </el-collapse-item>
        </el-collapse>


      </el-form>

    </div>

    <div class="box registerBox" v-if="showLogin == false">
      <div class="title">
        <span class="t1">
          注册
        </span>
        <div class="t2" @click="closeLogin()">
          X
        </div>
      </div>
      <el-divider></el-divider>
      <el-form :rules="rules" :label-position="labelPosition" :model="registerForm" ref="registerForm">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="registerForm.userName" placeholder="用户名长度在5~20之间" :disabled="loginType.password"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="registerForm.nickname" placeholder="昵称长度在1~20之间" :disabled="loginType.password"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerForm.password" placeholder="密码长度在5~20之间" :disabled="loginType.password"></el-input>
        </el-form-item>

        <el-form-item label="重复密码" prop="password2">
          <el-input type="password" v-model="registerForm.password2" placeholder="请再次输入密码" :disabled="loginType.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入正确的邮箱进行注册认证" :disabled="loginType.password"></el-input>
        </el-form-item>

        <el-row class="btn">
          <el-button class="loginBtn" type="primary" @click="startRegister" :disabled="loginType.password">注册</el-button>
          <el-button class="registerBtn" type="info" @click="goLogin" :disabled="loginType.password">返回登录</el-button>
        </el-row>

        <div class="loginTip">注册后，需要到邮箱进行邮件认证~</div>
      </el-form>
    </div>

    <div class="mask"></div>

  </div>
</template>

<script>
import {login, localLogin, localRegister, getWechatOrCodeTicket, getUserLoginStatus, getWeChatLoginUrl} from "@/api/user";
import {getLoginKey,loginCheck } from "@/api/wechat";

import { Loading } from 'element-ui';
import {setCookie} from "@/utils/cookieUtils";
import {mapMutations} from "vuex";
import Qrcode from 'vue-qrcode-component'
export default {
  name: "share",
  data() {
    return {
      loading: null,
      option: {
        fullscreen: true,
        lock: true
      },
      webConfig: {},
      vueMoguWebUrl: process.env.VUE_DIDIOK_WEB,
      showPasswordLogin: true, // 是否显示账号密码登录
      showPersonWechatLogin: false, // 是否展示微信登录
      wechatOrCode: "", // 微信公众号登录二维码
      ticket: "", // 用户的票券
      wechatLoginKey: "", // 验证码
      interval: null,
      // 显示登录页面
      showLogin: true,
      isLogin: false,
      table: false,
      dialog: false,
      labelPosition: "right",
      loginForm: {
        userName: "",
        password: ""
      },
      registerForm: {
        userName: "",
        password: "",
        password2: "",
        email: ""
      },
      // 登录类别
      loginType: {
        password: true,
        gitee: true,
        github: true,
        qq: true,
        wechat: true,
        personWechat: true,
      },
      loginRules: {
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          { min: 5, message: "用户名长度大于等于 5 个字符", trigger: "blur" },
          { max: 20, message: "用户名长度不能大于 20 个字符", trigger: "blur" }
        ],
        nickname: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          { min: 1, message: "用户名长度大于等于 1 个字符", trigger: "blur" },
          { max: 20, message: "用户名长度不能大于 20 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, message: "密码长度需要大于等于 5 个字符", trigger: "blur" },
          { max: 20, message: "密码长度不能大于 20 个字符", trigger: "blur" }
        ]
      },
      rules: {
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          { min: 5, message: "用户名长度大于等于 5 个字符", trigger: "blur" },
          { max: 20, message: "用户名长度不能大于 20 个字符", trigger: "blur" }
        ],
        nickname: [
          {required: true, message: '请输入昵称', trigger: 'blur'}
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, message: "密码长度需要大于等于 5 个字符", trigger: "blur" },
          { max: 20, message: "密码长度不能大于 20 个字符", trigger: "blur" }
        ],
        password2: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { min: 5, message: "密码长度需要大于等于 5 个字符", trigger: "blur" },
          { max: 20, message: "密码长度不能大于 20 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          {pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/, message: '请输入正确的邮箱'},
        ]
      }
    };
  },
  components: {
    Qrcode
  },
  created() {
    this.setLoginTypeList()
  },
  methods: {
    ...mapMutations(['setUserInfo', 'setLoginState']),
    setLoginTypeList: function() {
      // 获取登录方式列表
      let webConfigData = this.$store.state.app.webConfigData
      this.webConfig = webConfigData
      if(webConfigData.loginTypeList != undefined) {
        let loginTypeList = JSON.parse(webConfigData.loginTypeList)
        for(let a=0; a<loginTypeList.length; a++) {
          switch (loginTypeList[a]) {
            case "1": {
              this.loginType.password = false
            } break;
            case "2": {
              this.loginType.gitee = false
            } break;
            case "3": {
              this.loginType.github = false
            } break;
            case "4": {
              this.loginType.qq = false
            } break;
            case "5": {
              // 公众号
              this.loginType.wechat = false
            } break;
            case "7": {
              // 个人微信
              this.loginType.personWechat = false
            } break;
            default: {
              console.log("登录方式设置有误！！")
            }
          }
        }

        // 控制一下优先级 1 账号密码 5 微信公众号 7 微信
        let isShow = false
        if(webConfigData.loginPriority) {
          let loginPriority = webConfigData.loginPriority
          isShow = true
          if (loginPriority === "1") {
            this.showPasswordLogin = true
            this.showPersonWechatLogin = false
          }
          if (loginPriority === "5") {
            this.showPasswordLogin = false
            this.showPersonWechatLogin = false
          }
          if (loginPriority === "7") {
            this.showPasswordLogin = false
            this.showPersonWechatLogin = true
          }
        }
        if (!isShow) {
          // 只有当开启微信登录，并且未账号密码时，才主动显示扫码页面
          this.showPasswordLogin = !(this.loginType.password && !this.loginType.wechat)
        }

        if(!this.showPasswordLogin) {
          this.getWechatLoginKey()
        }
      }
    },
    getWeChatLoginUrlMethod() {
      let that = this
      let params = new URLSearchParams()
      params.append("operateType", "login")
      getWeChatLoginUrl(params).then(response => {
        if (response.code === this.$ECode.SUCCESS) {
          console.log("获取微信的信息", response)
          let data = response.data;
          let obj = new WxLogin({
            // 需要显示内嵌二维码的容器id
            id: 'login_container',
            self_redirect:true,
            // 应用ID
            appid: data.appId,
            // 网页默认即可
            scope: data.scope,
            // 授权成功后回调的url
            redirect_uri: encodeURIComponent(data.redirect_uri),
            // 可设置为简单的随机数加session用来校验
            state: data.state,
            // 二维码的样式，提供"black"、"white"可选。
            style: 'black',
            // 自定义样式链接
            href: 'https://oos.moguit.cn/cdn/wechatLogin.css'
          })

          // 开始定时扫描，判断是否完成登录
          let count = 0
          let interval = setInterval(() => {
            count++
            // 当检查15次未扫码的时候，将二维码失效，重试关闭接口请求
            if(count > 30) {
              that.wechatLoginKey.loginKey = "验证码失效,请刷新"
              clearInterval(interval)
            }
            let params = {}
            params.code = data.loginKey
            params.ticket = data.ticket
            loginCheck(params).then(response => {
              console.log("获取用户状态", response)
              if(response.code == that.$ECode.SUCCESS) {
                console.log("获取token", response)
                // 设置token到Cookie中，并刷新页面
                let token = response.data
                if (token) {
                  setCookie("token", token, 31)
                  location.reload();
                }
              }
            });
          }, 3000);

        }
      })
    },
    startLogin: function () {
      let that = this
      // 记录跳转地址，后续登录后做跳转到此页面
      setCookie("redirectUrl", that.$route.path, 1);
      that.$refs.loginForm.validate((valid) => {
        if(!valid) {
          console.log('校验失败')
          return;
        } else {
          let params = {};
          params.userName = that.loginForm.userName;
          params.password = that.loginForm.password;
          params.isRememberMe = 1;
          localLogin(params).then(response => {
            if (response.code == that.$ECode.SUCCESS) {
              console.log("登录成功的消息", "?token=" + response.data.token)
              // 跳转到首页
              window.location.replace("?token=" + response.data.token)
            } else {
              that.$message({
                type: "error",
                message: response.message
              })
            }
          });
        }
      })
    },
    startRegister: function () {
      this.$refs.registerForm.validate((valid) => {
        if(!valid) {
          console.log('校验失败')
          return;
        } else {
          let password = this.registerForm.password;
          let password2 = this.registerForm.password2;
          if(password != password2) {
            this.$message({
              type: "success",
              message: "两次密码不一致"
            })
            return;
          }
          let params = {};
          params.userName = this.registerForm.userName;
          params.password = this.registerForm.password;
          params.email = this.registerForm.email;
          params.nickname = this.registerForm.nickname
          localRegister(params).then(response => {
            if (response.code == this.$ECode.SUCCESS) {
              this.$message({
                type: "success",
                message: response.data
              })
              // 打开登录页面
              this.goLogin();
            } else {
              this.$message({
                type: "error",
                message: response.message
              })
            }
          });
        }
      })
    },
    goLogin: function () {
      this.showLogin = true;
    },
    goRegister: function () {
      this.registerForm.userName="";
      this.registerForm.password="";
      this.registerForm.password2="";
      this.registerForm.email="";
      this.showLogin = false;
    },
    userInfoStatus: function () {
      getUserLoginStatus().then(response => {
        console.log("获取用户状态", response)
      });
    },
    refreshWechat: function () {
      clearInterval(this.interval)
      this.getWechatLoginKey()
      this.$message.success("刷新成功")
    },
    // 获取验证码
    getWechatLoginKey: function () {
      this.showPasswordLogin = false
      let that = this
      getLoginKey().then(response => {
        if (response.code == this.$ECode.SUCCESS) {
          let loginKey = response.data
          this.wechatLoginKey = loginKey
          let count = 0
          let interval = setInterval(() => {
            count++
            // 当检查15次未扫码的时候，将二维码失效，重试关闭接口请求
            if(count > 30) {
              that.wechatLoginKey.loginKey = "验证码失效,请刷新"
              clearInterval(interval)
            }
            let params = {}
            params.code = loginKey.loginKey
            params.ticket = loginKey.ticket
            loginCheck(params).then(response => {
              console.log("获取用户状态", response)
              if(response.code == that.$ECode.SUCCESS) {
                console.log("获取token", response)
                // 判断url中是否含有token
                let token = response.data
                if (token != undefined) {
                  // 设置token七天过期
                  setCookie("token", token, 31)
                  location.reload();
                }
              }
            });
          }, 3000);

          this.interval = interval
        }
      })
    },
    goAuth: function (source) {
      this.showPersonWechatLogin = false
      // 记录跳转地址，后续登录后做跳转到此页面
      setCookie("redirectUrl", this.$route.path, 1);
      // 判断是否点击公众号登录
      if(source === "wechat") {
        console.log("点击公众号登录")
        this.getWechatLoginKey()
        return
      }
      if(source === "password") {
        console.log("点击账号密码登录")
        this.showPersonWechatLogin = false
        this.showPasswordLogin = true
        return
      }
      if(source === "personWechat") {
        this.showPersonWechatLogin = true
        console.log("点击微信登录")
        this.getWeChatLoginUrlMethod()
        return
      }
      this.loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let params = new URLSearchParams();
      params.append("source", source);
      params.append("type", "login");
      login(params).then(response => {
        if (response.code == this.$ECode.SUCCESS) {
          window.location.href = response.data.url
        }
      });
    },
    closeLogin: function() {
      this.$emit("closeLoginBox", "");
    }
  }
};
</script>

<style>

.loginBox {
  border-radius: 5px;
}

.box {
  width: 400px;
  height: 420px;
  background: white;
  position: fixed;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 101; /* 要比遮罩层大 */
}

.registerBox {
  height: 680px;
}

.box .title {
  height: 48px;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  line-height: 48px;
}
.box .title .t2 {
  font-size: 16px;
  float: right;
  margin-right: 6px;
  margin-top: -6px;
  cursor: pointer;
}

.box .el-divider--horizontal {
  margin: 12px 0;
}

.box .el-form-item__label {
  margin-left: 10px;
  font-size: 16px;
}

.box .el-input__inner {
  margin-left: 10px;
  width: 90%;
}

.box .btn {
  text-align: center;
}

.box .loginBtn {
  width: 40%;
}

.box .registerBtn {
  width: 40%;
}

.elRow {
  margin-top: 15px;
  text-align: center;
}

.loginTip {
  margin-top: 10px;
  font-size: 12px;
  text-align: center;
  color: #bababa;
}

.remarksBox {
  position: fixed;
  left: 50%;
  margin-left: -100px;
  top: 50%;
  margin-top: -50px;
  border: 1px solid red;
  width: 200px;
  height: 100px;
  text-align: center;
  z-index: 101; /* 要比遮罩层大 */
}

/* 遮罩层 */
.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

#login_container iframe {
  height: 230px;
}
</style>
